Page({

  data: {
    message: null,
    authorInformation: null,
    comments: null,
    motto: '知乎--微信小程序版',
    userInfo: {}
  },

  
  onLoad: function (options) {
    getMessageById(options.messageId,this);
    getCommentsById(options.messageId,this);
  },


  onPullDownRefresh: function(){
    var options = {};
    options.messageId = this.data.message.messageId;
    this.onLoad(options);
  },

  goToDiscussion: function(){
    wx.createSelectorQuery()
      .select("#discussion")
      .boundingClientRect(function (rect) {
        wx.pageScrollTo({
          scrollTop: rect.top,
          duration: 300
        });
      })
      .exec();
  },

  addComment: function(){
    wx.navigateTo({
      url: '../addComment/addComment?messageId=' + this.data.message.messageId,
    })
  }
  
});

const getCommentsById = function (messageId, _this){
  wx.request({
    url: 'https://dorm.dormassistant.wang:8080/comment/queryAllByMessageId',
    method: "GET",
    data: {
      messageId: messageId
    },
    success: function (res) {

      var tempComments = res.data.comments;
      for (var i = 0; i < tempComments.length; i += 1) {
        tempComments[i].time = tempComments[i].time.split("T")[0];
      }

      _this.setData({
        comments: tempComments
      });
      console.log(_this.data.comments);
    }
    
  });

}


const getMessageById = function (messageId, _this) {
  wx.request({
    url: 'https://dorm.dormassistant.wang:8080/message/getMessageByMessageId',
    method: "GET",
    data: {
      messageId: messageId
    },
    success: function (res) {
      getAuthorInfo(res.data.message.userId,_this);
      _this.setData({
        message: res.data.message
      });
      console.log(_this.data.message);
    },
    fail: function (res) {
      var toastText = '数据获取失败';
      wx.showToast({
        title: toastText,
        icon: '',
        duration: 2000
      });
    }
  });
}

const getAuthorInfo = function (authorId, _this){

  wx.request({
    url: 'https://dorm.dormassistant.wang:8080/userInformation/queryUserInformationById',
    data: {
      userId: authorId
    },
    method: "GET",
    success: function (res) {
      _this.setData({
        authorInformation: res.data.user
      });
      console.log(_this.data.authorInformation);
    }
  });

}